package logic
/**
业务层
 */
import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"strings"
	"time"
)

// 获取到期的任务
func (p *Timer) getExpireJobs() ([]string, error) {
	conn := p.Pool.Get()
	defer conn.Close()
	return redis.Strings(conn.Do("ZRANGEBYSCORE", KEY_JOB_POOL, "0", time.Now().Unix()))
}

// 获取任务的Topic
func (p *Timer) getJobTopic(jobID string, ch chan []string) {
	conn := p.Pool.Get()
	defer conn.Close()
	//获取任务的标题
	topic, err := redis.Strings(conn.Do("HMGET", PREFIX_JOB_BUCKET+jobID, "topic"))
	if (err != nil) {
		p.HandleError(err, "getJobTopic", jobID)
		ch <- []string{jobID, ""}
		return
	}
	//并将任务ID和任务标题组合成数组传给通道
	arr := []string{jobID, topic[0]}
	ch <- arr
}

// 移动任务至ReadyQueue
func (p *Timer) moveJobToReadyQueue( topic string,jobIDs []string) {
	// 获取连接
	conn := p.Pool.Get()
	defer conn.Close()
	jobIDsStr := strings.Join(jobIDs, ",")
	// 开启事物
	if err := p.startTrans(conn); err != nil {
		p.HandleError(err, "startTrans", jobIDsStr)
		return
	}
	// 从zset中删除过期的任务ID
	if err := p.delJobPool(conn, jobIDs, topic); err != nil {
		p.HandleError(err, "delJobPool", jobIDsStr)
		return
	}
	// 并将过期任务ID插入只读队列
	if err := p.addReadyQueue(conn, jobIDs, topic); err != nil {
		p.HandleError(err, "addReadyQueue", jobIDsStr)
		return
	}
	// 提交事物
	values, err := p.commit(conn)
	if err != nil {
		p.HandleError(err, "commit", jobIDsStr)
		return
	}
	// 事务结果处理
	v := values[0].(int64)
	v1 := values[1].(int64)
	if v == 0 || v1 == 0 {
		p.HandleError(err, "commit", jobIDsStr)
		return
	}
	// 打印日志
	p.Logger.Info(fmt.Sprintf("Job is ready, Topic: %s, IDs: [%s]", topic, jobIDsStr))
}
